package esmp.jtt808;

import esmp.jtt808.command.Jtt808Cmd;
import netty.session.NettySession;
import netty.session.SessionManager;
import redis.task.DeferredResultTask;
import redis.task.DeferredResultTaskManager;
import redis.task.DeferredResultTaskResult;

import java.util.concurrent.CompletableFuture;

/**
 * Created by dave on 18-7-20 下午9:33.
 * 808协议指令下发执行类
 */
public class JTT808CmdExecutor {
    public static final String TASK_PREFIX = "netty.";
    private String localServerId;
    private SessionManager sessionManager;
    private DeferredResultTaskManager taskManager;

    public JTT808CmdExecutor(String localServerId, SessionManager sm, DeferredResultTaskManager tm) {
        this.localServerId = localServerId;
        this.sessionManager = sm;
        this.taskManager = tm;
    }

    /**
     * 向设备下发指令
     * @param sessionId sessionId，通常为SIM卡号
     * @param cmdType
     * @param data 指令消息体对象
     * @return
     */
    public CompletableFuture<DeferredResultTaskResult<Object>> execute(String sessionId, Jtt808Cmd cmdType, Object data) {
        NettySession session = sessionManager.getSession(sessionId);
        DeferredResultTask<?> task = new DeferredResultTask<>(session.getServerId(), localServerId, sessionId, TASK_PREFIX + cmdType.name(), data);
        return taskManager.executeAndGetResult(task);
    }
}
